using System;
using System.Collections.Generic;
using Castle.ActiveRecord;
using NHibernate.Expression;
using Sport.Site.Models;

namespace GettingStartedSample.Models
{
    [ActiveRecord]
    public class Meeting : ActiveRecordBase<Meeting>
    {

        public Meeting(Player host, Venue venue, Activity activity, DateTime date, string description)
        {
            Host = host;
            Venue = venue;
            Activity = activity;
            Date = date;
            Description = description;
        }

        public Meeting(){}

        [PrimaryKey]
        public Int64 Id { get; set; }

        [BelongsTo("PlayerId")]
        public Player Host {get; set;}

        [BelongsTo("ActivityId")]
        public Activity Activity{get;set; }

        [BelongsTo("VenueId")]
        public Venue Venue { get; set; }

        [Property]
        public DateTime Date{ get; set; }

        [Property]
        public string Description{ get; set; }

        [HasAndBelongsToMany(typeof(Player), 
        Table="PlayerMeeting", ColumnKey="meetingId", ColumnRef="playerId")]
        public IList<Player> Players{ get; set; }

        public static Meeting FindById(Int64 id)
        {
            return FindByPrimaryKey(id); 
        }

        public bool AddPlayer(Player player)
        {
            if (Players.Contains(player)) return false;
            Players.Add(player);
            return true;
        }

        public static List<Meeting> FindAll(Activity activity)
        {
            var equalsActivity = Expression.Eq("Activity", activity);
            var meetings = FindAll(new Order[]{}, new ICriterion[]{equalsActivity});
            return new List<Meeting>(meetings);
        }

        public static List<Meeting> FindAll(string venue, string activity)
        {
            var equalsActivity = Expression.Eq("Activity", activity);
            var meetings = FindAll(new Order[] { }, new ICriterion[] { equalsActivity });
            return new List<Meeting>(meetings);
        }

        public static List<Meeting> FindBy(Venue venue, Activity activity)
        {

            var equalsActivity = Expression.Eq("Activity", activity);
            var equalsVenue = Expression.Eq("Venue", venue);
            var meetings = FindAll(new Order[] { }, new ICriterion[] { equalsActivity, equalsVenue });
            return new List<Meeting>(meetings);
        }
    }
}